<template>
  <div class="register-view">
    <div class="register-container">
      <div class="register-card">
        <h2>注册</h2>
        
        <!-- 用户类型选择 -->
        <div class="user-type-selector">
          <el-radio-group v-model="registerForm.userType" size="large" @change="handleUserTypeChange">
            <el-radio-button label="user">普通用户</el-radio-button>
            <el-radio-button label="merchant">商家</el-radio-button>
          </el-radio-group>
        </div>
        
        <el-form :model="registerForm" :rules="rules" ref="registerFormRef" label-width="0">
          <!-- 通用字段 -->
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              :placeholder="userType === 'user' ? '请输入用户名' : '请输入商家用户名'"
              prefix-icon="User"
              size="large"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请确认密码"
              prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          
          <!-- 商家专用字段 -->
          <template v-if="userType === 'merchant'">
            <el-form-item prop="merchantName">
              <el-input
                v-model="registerForm.merchantName"
                placeholder="请输入商家名称"
                prefix-icon="Shop"
                size="large"
              />
            </el-form-item>
            
            <el-form-item prop="contactPhone">
              <el-input
                v-model="registerForm.contactPhone"
                placeholder="请输入联系电话"
                prefix-icon="Phone"
                size="large"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
            
            <el-form-item prop="merchantAddress">
              <el-input
                v-model="registerForm.merchantAddress"
                placeholder="请输入商家地址"
                prefix-icon="Location"
                size="large"
              />
            </el-form-item>
            
            <el-form-item prop="businessHours">
              <el-input
                v-model="registerForm.businessHours"
                placeholder="营业时间（如：9:00-22:00）"
                prefix-icon="Clock"
                size="large"
              />
            </el-form-item>
            
            <el-form-item prop="merchantDescription">
              <el-input
                v-model="registerForm.merchantDescription"
                type="textarea"
                :rows="3"
                placeholder="请简单介绍您的商家特色..."
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </template>
          
          <el-form-item prop="agree">
            <el-checkbox v-model="registerForm.agree">
              我已阅读并同意<a href="#" @click.prevent>《用户协议》</a>和<a href="#" @click.prevent>《隐私政策》</a>
            </el-checkbox>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" size="large" style="width: 100%;" @click="handleRegister" :loading="loading">
              {{ userType === 'user' ? '注册' : '提交商家申请' }}
            </el-button>
          </el-form-item>
        </el-form>
        
        <div class="register-links">
          <router-link to="/login">已有账号？立即登录</router-link>
        </div>
        
        <!-- 商家注册说明 -->
        <div v-if="userType === 'merchant'" class="merchant-note">
          <el-alert
            title="商家注册说明"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <p>• 商家注册后需要管理员审核通过才能正常使用</p>
              <p>• 请确保提供的信息真实有效</p>
              <p>• 审核通过后您将收到通知</p>
            </template>
          </el-alert>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
  name: 'RegisterView',
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    
    return {
      loading: false,
      registerForm: {
        userType: 'user',
        username: '',
        password: '',
        confirmPassword: '',
        // 商家专用字段
        merchantName: '',
        contactPhone: '',
        merchantAddress: '',
        businessHours: '9:00-22:00',
        merchantDescription: '',
        agree: false
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        merchantName: [
          { required: true, message: '请输入商家名称', trigger: 'blur' },
          { min: 2, max: 50, message: '商家名称长度在2到50个字符', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { max: 20, message: '联系电话不能超过20个字符', trigger: 'blur' }
        ],
        merchantAddress: [
          { required: true, message: '请输入商家地址', trigger: 'blur' },
          { min: 5, max: 100, message: '地址长度在5到100个字符', trigger: 'blur' }
        ],
        businessHours: [
          { required: true, message: '请输入营业时间', trigger: 'blur' }
        ],
        merchantDescription: [
          { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
        ],
        agree: [
          { 
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请同意用户协议'))
              } else {
                callback()
              }
            }, 
            trigger: 'change' 
          }
        ]
      }
    }
  },
  computed: {
    userType() {
      return this.registerForm.userType
    }
  },
  methods: {
    handleUserTypeChange() {
      // 清空表单数据（除了用户类型）
      const userType = this.registerForm.userType
      this.registerForm = {
        userType,
        username: '',
        password: '',
        confirmPassword: '',
        merchantName: '',
        contactPhone: '',
        merchantAddress: '',
        businessHours: '9:00-22:00',
        merchantDescription: '',
        agree: false
      }
      // 清除验证错误
      this.$nextTick(() => {
        this.$refs.registerFormRef?.clearValidate()
      })
    },
    
    async handleRegister() {
      try {
        await this.$refs.registerFormRef.validate()
        this.loading = true
        
        // 准备注册数据
        const registerData = {
          username: this.registerForm.username,
          password: this.registerForm.password,
          userType: this.registerForm.userType
        }
        
        // 如果是商家注册，添加商家信息
        if (this.userType === 'merchant') {
          registerData.merchantName = this.registerForm.merchantName
          registerData.merchantAddress = this.registerForm.merchantAddress
          registerData.contactPhone = this.registerForm.contactPhone
          registerData.businessHours = this.registerForm.businessHours
          registerData.merchantDescription = this.registerForm.merchantDescription
        }
        
        // 调用注册API
        const response = await fetch('http://localhost:2077/api/auth/register', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(registerData)
        })
        
        const result = await response.json()
        
        if (result.success) {
          if (this.userType === 'user') {
            ElMessage.success('用户注册成功！请登录')
          } else {
            ElMessage.success('商家申请提交成功！请等待管理员审核')
          }
          this.$router.push('/login')
        } else {
          ElMessage.error(result.message || '注册失败')
        }
        
      } catch (error) {
        console.error('注册错误:', error)
        ElMessage.error('网络错误，请稍后重试')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.register-view {
  min-height: 100vh;
  background: var(--gradient-accent);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-md);
  position: relative;
  overflow: hidden;
}

.register-view::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><radialGradient id="a" cx="50%" cy="50%"><stop offset="0%" stop-color="rgba(255,255,255,0.1)"/><stop offset="100%" stop-color="rgba(255,255,255,0)"/></radialGradient></defs><circle cx="20" cy="20" r="2" fill="url(%23a)"/><circle cx="80" cy="20" r="2" fill="url(%23a)"/><circle cx="20" cy="80" r="2" fill="url(%23a)"/><circle cx="80" cy="80" r="2" fill="url(%23a)"/><circle cx="50" cy="50" r="3" fill="url(%23a)"/></svg>') repeat;
  opacity: 0.3;
  animation: float 20s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-20px) rotate(180deg); }
}

.register-container {
  width: 100%;
  max-width: 500px;
  position: relative;
  z-index: 1;
}

.register-card {
  background: var(--background-primary);
  padding: var(--spacing-xl);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-xl);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  position: relative;
  overflow: hidden;
}

.register-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: var(--gradient-primary);
}

h2 {
  text-align: center;
  margin-bottom: var(--spacing-lg);
  color: var(--text-primary);
  font-weight: 700;
  font-size: 2rem;
  position: relative;
}

h2::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: var(--gradient-secondary);
  border-radius: var(--radius-xl);
}

.user-type-selector {
  margin-bottom: var(--spacing-xl);
  text-align: center;
}

.el-radio-group {
  width: 100%;
}

.el-radio-button {
  flex: 1;
}

.el-radio-button__inner {
  width: 100%;
  border-radius: var(--radius-md) !important;
  border: 2px solid var(--border-light) !important;
  background: var(--background-accent) !important;
  color: var(--text-secondary) !important;
  font-weight: 500 !important;
  transition: all 0.3s ease !important;
}

.el-radio-button__inner:hover {
  border-color: var(--primary-light) !important;
  background: var(--background-primary) !important;
  color: var(--text-primary) !important;
}

.el-radio-button.is-active .el-radio-button__inner {
  background: var(--gradient-primary) !important;
  border-color: var(--primary-color) !important;
  color: white !important;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3) !important;
}

.el-form-item {
  margin-bottom: var(--spacing-lg);
}

.el-input {
  height: 50px;
}

.el-input__wrapper {
  background: var(--background-accent) !important;
  border: 2px solid transparent !important;
  border-radius: var(--radius-lg) !important;
  transition: all 0.3s ease !important;
  box-shadow: none !important;
}

.el-input__wrapper:hover {
  border-color: var(--primary-light) !important;
  background: var(--background-primary) !important;
}

.el-input__wrapper.is-focus {
  border-color: var(--primary-color) !important;
  background: var(--background-primary) !important;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1) !important;
}

.el-textarea__inner {
  background: var(--background-accent) !important;
  border: 2px solid transparent !important;
  border-radius: var(--radius-lg) !important;
  transition: all 0.3s ease !important;
  resize: none !important;
}

.el-textarea__inner:hover {
  border-color: var(--primary-light) !important;
  background: var(--background-primary) !important;
}

.el-textarea__inner:focus {
  border-color: var(--primary-color) !important;
  background: var(--background-primary) !important;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1) !important;
}

.el-button {
  height: 50px !important;
  font-size: 1.1rem !important;
  font-weight: 600 !important;
  border-radius: var(--radius-lg) !important;
  transition: all 0.3s ease !important;
}

.el-button--primary {
  background: var(--gradient-primary) !important;
  border: none !important;
  position: relative;
  overflow: hidden;
}

.el-button--primary::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
  transition: left 0.5s;
}

.el-button--primary:hover::before {
  left: 100%;
}

.el-checkbox {
  margin: var(--spacing-md) 0;
}

.register-links {
  text-align: center;
  margin-top: var(--spacing-lg);
  padding-top: var(--spacing-md);
  border-top: 1px solid var(--border-light);
}

.register-links a {
  color: var(--primary-color);
  text-decoration: none;
  font-size: 0.95rem;
  font-weight: 500;
  transition: all 0.3s ease;
  position: relative;
}

.register-links a::after {
  content: '';
  position: absolute;
  width: 0;
  height: 2px;
  bottom: -2px;
  left: 50%;
  background: var(--gradient-secondary);
  transition: all 0.3s ease;
}

.register-links a:hover {
  color: var(--secondary-color);
}

.register-links a:hover::after {
  width: 100%;
  left: 0;
}

.merchant-note {
  margin-top: var(--spacing-lg);
}

.merchant-note .el-alert {
  border-radius: var(--radius-lg) !important;
  background: rgba(59, 130, 246, 0.1) !important;
  border: 1px solid rgba(59, 130, 246, 0.2) !important;
}

.merchant-note .el-alert__content p {
  margin: 4px 0;
  font-size: 0.9rem;
  color: var(--text-secondary);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-view {
    padding: var(--spacing-sm);
  }
  
  .register-card {
    padding: var(--spacing-lg);
  }
  
  h2 {
    font-size: 1.75rem;
  }
  
  .el-radio-button__inner {
    font-size: 0.9rem !important;
    padding: 8px 12px !important;
  }
}

/* 输入框图标样式 */
.el-input__prefix-inner {
  color: var(--text-secondary) !important;
}

.el-input__wrapper.is-focus .el-input__prefix-inner {
  color: var(--primary-color) !important;
}
</style> 